package cn.wyu.blogrest.controller;

import cn.wyu.blogrest.Exception.AuthException;
import cn.wyu.blogrest.entity.Auth;
import cn.wyu.blogrest.entity.User;
import cn.wyu.blogrest.repository.UserRepository;
import cn.wyu.blogrest.service.AuthService;
import cn.wyu.blogrest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
@Transactional
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AuthService authService;

    @RequestMapping("/init")
    public String initUser(){
        this.userService.initUsers();
        return "initUser access";
    }

    /**
     * 验证用户身份，生成accessToken
     */
    @RequestMapping(value = "/auth",method = RequestMethod.POST)
    public Auth auth(User user){
        User authUser = this.userService.auth(user);
        if(authUser!=null){
            Auth auth = this.authService.getAccessToken(authUser);
            return  auth;
        }
        //验证不通过
         throw  new AuthException("Auth fail");
    }

    /**
     * 获取用户信息
     */

    @RequestMapping(value = "/{userId}",method = RequestMethod.GET)
    public User userGet(@PathVariable int userId){
        return this.userRepository.findById(userId);
    }
}
